﻿using System;
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Server.Kestrel.Https;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Serilog;
using Serilog.Events;

namespace Ids2OpenId;

public class Program
{
    public async static Task<int> Main(string[] args)
    {
        Log.Logger = new LoggerConfiguration()
#if DEBUG
            .MinimumLevel.Debug()
#else
            .MinimumLevel.Information()
#endif
            .MinimumLevel.Override("Microsoft", LogEventLevel.Information)
            .MinimumLevel.Override("Microsoft.EntityFrameworkCore", LogEventLevel.Warning)
            .Enrich.FromLogContext()
            .WriteTo.Async(c => c.File("Logs/logs.txt"))
            .WriteTo.Async(c => c.Console())
            .CreateLogger();

        try
        {
            Log.Information("Starting Ids2OpenId.HttpApi.Host.");
            var builder = WebApplication.CreateBuilder(args);

            // 配置 HTTPS 证书认证
            builder.WebHost.ConfigureKestrel(serverOptions =>
            {
                serverOptions.ListenAnyIP(44324, options =>
                {
                    var baseDir = Path.GetDirectoryName(typeof(Program).Assembly.Location)
                        ?? throw new InvalidOperationException("程序集 IDSReferenceTokenHttpApiHostModule 目录为空！");

                    var pfxFile = Path.Combine(baseDir, "Assets/Https/certificate.pfx");
                    var password = "1q2w3e*";
                    if (!File.Exists(pfxFile)) throw new InvalidOperationException($"{pfxFile} is not found.");

                    var cert = new X509Certificate2(pfxFile, password);
                    options.UseHttps(cert);
                });

                serverOptions.ConfigureHttpsDefaults(listenOptions =>
                {
                    listenOptions.ClientCertificateMode = ClientCertificateMode.AllowCertificate;
                    listenOptions.SslProtocols = SslProtocols.Tls13 | SslProtocols.Tls12;
                });
            });

            builder.Host.AddAppSettingsSecretsJson()
                .UseAutofac()
                .UseSerilog();
            await builder.AddApplicationAsync<Ids2OpenIdHttpApiHostModule>();
            var app = builder.Build();
            await app.InitializeApplicationAsync();
            await app.RunAsync();
            return 0;
        }
        catch (Exception ex)
        {
            Log.Fatal(ex, "Host terminated unexpectedly!");
            return 1;
        }
        finally
        {
            Log.CloseAndFlush();
        }
    }
}
